package com.tanhua.bg.service;


import cn.hutool.core.util.StrUtil;
import com.tanhua.bg.pojo.Log;
import com.tanhua.bg.vo.LogPageQueryParam;
import com.tanhua.bg.vo.PageResult;


import org.apache.commons.collections4.CollectionUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;


@Component
@Service
public class LogService {

    @Autowired
    private MongoTemplate mongoTemplate;


    //来自LogController,查询日志记录
    public PageResult queryLogPage(String token, LogPageQueryParam param) {

        //先校验token


        //----------------现在没有用户


        //定义结果对象，填充页数和每页大小
        PageResult pageResult = new PageResult();
        pageResult.setPage(param.getPage());
        pageResult.setPagesize(param.getPagesize());


        //获取query参数里面需要进行下面操作的类型参数
        Integer page = param.getPage();
        Integer pageSize = param.getPagesize();
        String sortOrder = param.getSortOrder();        //ascending 升序 descending 降序
        String sortProp = param.getSortProp();         //排序字段
        Long uid = param.getUid();

        PageRequest pageRequest=null;



        //根据日志时间logTime进行排序
        if (StrUtil.equals(sortOrder, "ascending")) {

            pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.asc("logTime")));


        }else {
            pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("logTime")));
        }










        //构建查询对象
       Query query = new Query();
        query.with(pageRequest);
        //去mongoDB查询登录记录
        List<Log> logList = this.mongoTemplate.find(query, Log.class);
        //如果查询记录为空返回空
        if (CollectionUtils.isEmpty(logList)) {
            return pageResult;
        }


        //这里缺少封装登录者信息什么的，暂时没有
        //-------------------------------


        //如果不为空就将日志集合放入结果对象返回
        pageResult.setItems(logList);


        return pageResult;
    }


}
